package cn.javadog.cloud.starter.jsonfilter.converter;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import cn.javadog.cloud.starter.jsonfilter.domain.JsonFilterObject;

import java.util.HashSet;

/**
 * @author yuy
 * @date 2020/7/2 10:43
 * @desc 对SimplePropertyPreFilter进行一层封装
 *
 * github：https://github.com/alibaba/fastjson/wiki/%E4%BD%BF%E7%94%A8SimplePropertyPreFilter%E8%BF%87%E6%BB%A4%E5%B1%9E%E6%80%A7
 **/
public class SimpleSerializerFilter extends SimplePropertyPreFilter {
    private final boolean exclude;
    private final Class<?> clazz;
    private final HashSet<String> fields;

    public SimpleSerializerFilter(JsonFilterObject jsonFilterObject) {
        this.exclude = jsonFilterObject.isExclude();
        this.fields = jsonFilterObject.getFields();
        this.clazz = jsonFilterObject.getClazz();
    }

    @Override
    public boolean apply(JSONSerializer serializer, Object source, String name) {
        // 必须类型匹配，暂不处理超类 clazz.isAssignableFrom(source.getClass())
        return source.getClass().equals(clazz) && exclude != fields.contains(name);
    }

}
